# -*- coding: utf-8 -*-
""" mylogger
"""

import logging, os, string, time, threading, types

FATAL = logging.FATAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG


class mylogger:
    """ """
    def __init__(self, log_file, log_tokens, log_level, newline='\n', backup=5):
        """ """
        self.LOG_FILE = log_file
        self.LOG_TOKENS = log_tokens
        self.LOG_LEVEL = log_level
        self.LOG_NEWLINE = newline
        self.loglock = threading.Lock()
        while backup > 1:
            backup -= 1
            self.tryBackupFile(self.LOG_FILE + "." + str(backup), self.LOG_FILE + "." + str(backup + 1))
        self.tryBackupFile(self.LOG_FILE, self.LOG_FILE + "." + str(backup))
        logfile = open(self.LOG_FILE, 'w')
        logfile.close()

    def log(self, token, level, msg):
        if (token not in self.LOG_TOKENS) and (self.LOG_TOKENS != 'all'):
            return
        if level < self.LOG_LEVEL:
            return
        self.loglock.acquire()
        f = open(self.LOG_FILE, 'a')
        f.write(time.asctime(time.localtime(time.time()))[4:] + ": ")
        f.write(token + ': ' + msg + self.LOG_NEWLINE)
        f.close()
        self.loglock.release()

    def fatal(self, token, msg):
        self.log(token, FATAL, msg)

    def error(self, token, msg):
        self.log(token, ERROR, msg)

    def warning(self, token, msg):
        self.log(token, WARNING, msg)

    def info(self, token, msg):
        self.log(token, INFO, msg)

    def debug(self, token, msg):
        self.log(token, DEBUG, msg)

    def tryBackupFile(self, old, new):
        try:
            os.rename(old, new)
        except OSError:
            pass
